package fule.com.playandroidkotlin.ui.fragment

import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import fule.com.playandroidkotlin.base.BaseFragment
import fule.com.playandroidkotlin.R
import fule.com.playandroidkotlin.ui.adapter.NavicgationTabAdapter
import fule.com.playandroidkotlin.ui.adapter.NavigationAdapter
import fule.com.playandroidkotlin.ui.model.NavigationModel
import fule.com.playandroidkotlin.ui.presenter.NavigationPresenter
import fule.com.playandroidkotlin.ui.view.NavigationView
import fule.com.playandroidkotlin.ui.weight.DividerDecoration
import kotlinx.android.synthetic.main.fm_navigation.*
import kotlinx.android.synthetic.main.toolbar.*

/**
 * 作者： njb
 * 时间： 2018/8/7 0007-下午 5:58
 * 描述： 导航
 * 来源：
 */
class NavigationFragment : BaseFragment<NavigationPresenter>(), (NavigationView) {
    override fun setTitle() {
        toolbar_title!!.text="导航"

    }

    private var tabdApter: NavicgationTabAdapter? = null
    private var list: List<NavigationModel.DataBean>? = null
    private var cid: String? = null
    private var navigationAdapter: NavigationAdapter? = null
    private var bScroll: Boolean = false
    private var currentIndex: Int = 0
    private var bClickTab: Boolean = false

    /**
     * linearLayoutManager
     */
    private val linearLayoutManager: LinearLayoutManager by lazy {
        LinearLayoutManager(activity)
    }


    override fun getLayoutId(): Int {
        return R.layout.fm_navigation
    }

    override fun loadData() {
        presenter!!.navi()
    }

    override fun initView() {
        initAdapter()
        initContentAdapter()
        leftRightLink()
    }

    override fun addListener() {
    }

    override fun createPresenter(): NavigationPresenter {
        return NavigationPresenter(this)
    }

    override fun showLoading() {
    }

    private fun initContentAdapter() {
        navigationAdapter = NavigationAdapter(null)
        var manager = LinearLayoutManager(context)
        rv_content.layoutManager = manager
        rv_content.addItemDecoration(DividerDecoration(ContextCompat.getColor(context!!,R.color.ce7e7e7), 1))
/*        navigationAdapter!!.bindToRecyclerView(rv_content)
        navigationAdapter!!.setEmptyView(R.layout.empty_layout_no_data)*/
        rv_content.adapter = navigationAdapter
        navigationAdapter!!.onItemClickListener = BaseQuickAdapter.OnItemClickListener { _, _, _ ->
        }

    }

    private fun initAdapter() {
        tabdApter = NavicgationTabAdapter(null)
        var manager = LinearLayoutManager(context)
        rv_tab.layoutManager = manager
        manager.orientation = LinearLayoutManager.VERTICAL
        rv_tab.addItemDecoration(DividerDecoration(ContextCompat.getColor(context!!,R.color.ce7e7e7), 1))
        rv_tab.adapter = tabdApter

        tabdApter!!.onItemClickListener = BaseQuickAdapter.OnItemClickListener { _, _, position ->
            list = tabdApter!!.data
            for (m in list!!) {
                m.isSelect = false
            }
            list!![position].isSelect = true
            cid = list!![position].cid.toString()
            bClickTab = true
            selectTab(position)
            tabdApter!!.notifyDataSetChanged()
        }
    }

    /**
     * Select Left TabLayout to Smooth Right RecyclerView
     */
    private fun selectTab(position: Int) {
        currentIndex = position
        rv_content.stopScroll()
        smoothScrollToPosition(position)
    }

    /**
     * Left TabLayout and Right RecyclerView Link
     */
    private fun leftRightLink() {
        rv_content.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                recyclerView.let { super.onScrollStateChanged(it, newState) }
                if (bScroll && (newState == RecyclerView.SCROLL_STATE_IDLE)) {
                    scrollRecyclerView()
                }
                rightLinkLeft(newState)
            }

            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                recyclerView.let { super.onScrolled(it, dx, dy) }
                if (bScroll) {
                    scrollRecyclerView()
                }
            }
        })

    }

    /**
     * Right RecyclerView link Left TabLayout
     *
     * @param newState RecyclerView Scroll State
     */
    private fun rightLinkLeft(newState: Int) {
        if (newState == RecyclerView.SCROLL_STATE_IDLE) {
            if (bClickTab) {
                bClickTab = false
                return
            }
            val firstPosition: Int = linearLayoutManager.findFirstVisibleItemPosition()
            if (firstPosition != currentIndex) {
                currentIndex = firstPosition
                setChecked(currentIndex)
            }
        }
    }

    private fun smoothScrollToPosition(position: Int) {
        val firstPosition: Int = linearLayoutManager.findFirstVisibleItemPosition()
        val lastPosition: Int = linearLayoutManager.findLastVisibleItemPosition()
        when {
            position <= firstPosition -> {
                rv_content.smoothScrollToPosition(position)
            }
            position <= lastPosition -> {
                val top: Int = rv_content.getChildAt(position - firstPosition).top
                rv_content.smoothScrollBy(0, top)
            }
            else -> {
                rv_content.smoothScrollToPosition(position)
                bScroll = true
            }
        }
    }

    /**
     * Smooth Right RecyclerView to Select Left TabLayout
     *
     * @param position checked position
     */
    private fun setChecked(position: Int) {
        if (bClickTab) {
            bClickTab = false
        } else {
            tabdApter!!.getItem(currentIndex)
        }
        currentIndex = position
    }

    private fun scrollRecyclerView() {
        bScroll = false
        val indexDistance: Int = currentIndex - linearLayoutManager.findFirstVisibleItemPosition()
        if (indexDistance > 0 && indexDistance < rv_content!!.childCount) {
            val top: Int = rv_content.getChildAt(indexDistance).top
            rv_content.smoothScrollBy(0, top)
        }
    }


    override fun onLoadNavi(data: List<NavigationModel.DataBean>) {
        tabdApter!!.setNewData(data)
        navigationAdapter!!.setNewData(data)
        data[0].isSelect = true
    }

}